package com.example.psychologicalappointmentsystem.tools;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

/**
 * ClassName TransactionIdGenerator
 * Description TODO 用来生成交易流水号
 * Date 2025/2/10 11:51
 * Version 1.0
 */
public class TransactionIdGenerator {
    // 使用AtomicLong保证线程安全
    private static final AtomicLong sequence = new AtomicLong(0);

    // 流水号长度
    private static final int SEQUENCE_LENGTH = 6;

    // 日期格式
    private static final String DATE_FORMAT = "yyyyMMddHHmmss";

    /**
     * 生成交易流水号
     *
     * @return 交易流水号
     */
    public static String generate() {
        // 1. 获取当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        String timestamp = dateFormat.format(new Date());

        // 2. 生成序列号
        long seq = sequence.getAndIncrement();
        if (seq >= Math.pow(10, SEQUENCE_LENGTH)) {
            sequence.set(0); // 如果序列号超过最大值，重置为0
            seq = sequence.getAndIncrement();
        }

        // 3. 格式化序列号，补零
        String sequenceStr = String.format("%0" + SEQUENCE_LENGTH + "d", seq);

        int random = (int) (Math.random() * 100); // 生成0-99的随机数
        String randomNum = String.format("%02d", random);

        // 4. 拼接流水号
        return timestamp + sequenceStr + randomNum;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(generate());
        }
    }
}
